package bai.demo.web;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.util.List;

/**
 * Created by Admin on 12/22 0022.
 */
public class DAOImp<T> implements DAO<T> {

    private Class<T> clazz;
    private QueryRunner queryRunner=new QueryRunner();
    public DAOImp(){
        Type superClass=getClass().getGenericSuperclass();
        if(superClass instanceof ParameterizedType){
            ParameterizedType parameterizedType= (ParameterizedType) superClass;
            Type[] types=parameterizedType.getActualTypeArguments();
            if(types !=null && types.length>0){
                clazz= (Class<T>) types[0];
            }
        }
    }


    @Override
    public void update(String sql, Object... args) {
        Connection connection=null;
        try{
            connection=JDBCUtil.getConnection();
            queryRunner.update(connection,sql,args);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(connection);
        }
    }

    @Override
    public T get(String sql, Object... args) {
        Connection connection=null;
        try{
            connection=JDBCUtil.getConnection();
            return queryRunner.query(connection,sql,new BeanHandler<>(clazz),args);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(connection);
        }
        return null;
    }

    @Override
    public List<T> getList(String sql, Object... args) {
        Connection connection=null;
        try{
            connection=JDBCUtil.getConnection();
            return queryRunner.query(connection,sql,new BeanListHandler<>(clazz),args);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(connection);
        }
        return null;
    }

    @Override
    public <E> E getForValue(String sql, Object... args) {
        Connection connection=null;
        try{
            connection=JDBCUtil.getConnection();
            return (E) queryRunner.query(connection,sql,new ScalarHandler(),args);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(connection);
        }
        return null;
    }
}
